package test;

import java.lang.invoke.MethodHandles;
import java.lang.invoke.VarHandle;

public class SingletonLockFree {
    private static VarHandle SINGLETON;
    private static VarHandle CREATED;
    private static boolean created;
    private static SingletonLockFree singleton;
    int x1, x2, x3, x4;
    int x5, x6, x7, x8;
    int y1, y2, y3, y4;
    int y5, y6, y7, y8;

    private SingletonLockFree(int v) {
        x1 = v;
        x2 = v;
        x3 = v;
        x4 = v;
        x5 = v;
        x6 = v;
        x7 = v;
        x8 = v;
        y1 = v;
        y2 = v;
        y3 = v;
        y4 = v;
        y5 = v;
        y6 = v;
        y7 = v;
        y8 = v;
    }

    static {
        try {
            SINGLETON = MethodHandles.lookup()
                    .findStaticVarHandle(SingletonLockFree.class, "singleton", SingletonLockFree.class);
            CREATED = MethodHandles.lookup()
                    .findStaticVarHandle(SingletonLockFree.class, "created", boolean.class);
        } catch (NoSuchFieldException | IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    public static SingletonLockFree getInstance(int v) {
        if (SINGLETON.getAcquire() == null) {
            if (CREATED.compareAndSet(false, true)) {
                SINGLETON.setRelease(new SingletonLockFree(v));
            } else {
                while (SINGLETON.getAcquire() == null) {

                }
            }
        }
        return (SingletonLockFree) SINGLETON.getAcquire();
    }

    public static void main(String[] args) {
        SingletonLockFree instance = SingletonLockFree.getInstance(2);
        System.out.println(instance);
        instance = SingletonLockFree.getInstance(3);
        System.out.println(instance);
    }
}
